from business import Business, DATE_TIME_FORMAT
from handler import MyAPIHandler
from datetime import datetime as dt


def query(business: Business, camera_id:int, start, end, limit:int=500):
    start = None if start is None or len(start.strip())==0 else dt.strptime(start, DATE_TIME_FORMAT)
    end = None if end is None or len(end.strip()) == 0 else dt.strptime(end, DATE_TIME_FORMAT)
    return business.query(camera_id, start, end, limit)


def get_last_distribute(camera_id:int, business: Business):
    return business.get_last_distribute(camera_id)


def download_img(img_id, business:Business, handler: MyAPIHandler):
    path = business.get_path_to_img(img_id)
    handler.json_response = False
    handler.set_header('Content-Type', 'image/%s' % business.iamges_name_ext)
    with open(path, 'rb') as file:
        while True:
            bs = file.read(business.img_block_size)
            handler.write(bs)
            if len(bs) < business.img_block_size:
                break
